package com.jsg.sl651.util;


import com.jsg.sl651.enums.ASCIICode;
import io.netty.buffer.ByteBuf;

import java.util.ArrayList;
import java.util.List;

public final class ByteUtil {

    public static String toHex(byte b) {
        // 将字节转换为整数，并使用 %x 格式化为十六进制字符串
        String hex = Integer.toHexString(b & 0xFF);
        // 如果十六进制字符串长度为1，则直接返回，否则返回后两位
//        return hex.length() == 1 ? hex : ;
        return (hex.length() == 2 ? hex : "0" + hex).toUpperCase();
    }

    public static byte toByte(String hex) {
        if (hex == null || hex.length() > 2 || hex.isEmpty()) {
            throw new IllegalArgumentException("Invalid hex string: " + hex);
        }
        if (hex.length() == 1) {
            hex = "0" + hex;
        }
        return (byte) Integer.parseInt(hex, 16);
    }

    public static String toHex(byte[] bytes) {
        return toHex(bytes,false);
    }

    public static String toHex(byte[] bytes, boolean prefix) {
        StringBuilder sb = new StringBuilder();
        if (prefix) {
            sb.append("0X");
        }
        for (byte b : bytes) {
            sb.append(toHex(b));
        }
        return sb.toString().trim();
    }

    public static byte[] toBytes(String hex) {
        if (hex == null || hex.isEmpty() || hex.length() % 2 != 0) {
            throw new IllegalArgumentException("Invalid hex string: " + hex);
        }
        hex = hex.toUpperCase();
        if (hex.startsWith("0X")) {
            hex = hex.substring(2);
        }
        byte[] bytes = new byte[hex.length() / 2];
        for (int i = 0; i < hex.length(); i += 2) {
            bytes[i / 2] = toByte(hex.substring(i, i + 2));
        }
        return bytes;
    }


    public static byte[] readBytes(ByteBuf data, int length) {
        byte[] bytes = new byte[length];
        data.readBytes(bytes);
        return bytes;
    }

    /**
     * 合并ASCII码到HEX码
     * <p>该方法的核心功能是将ASCII码字节数组转换为十六进制字节数组。</p>
     * <ul>
     *     <li>首先检查输入字节数组的长度是否为偶数。如果不是偶数，则抛出 {@link IllegalArgumentException} 异常。</li>
     *     <li>使用 {@link StringBuilder} 将ASCII码字节数组中的每个字节转换为字符，并拼接成一个字符串。</li>
     *     <li>调用 {@link #toBytes(String)} 方法将拼接后的字符串转换为十六进制字节数组。</li>
     * </ul>
     *
     * @param bytes ASCII码字节数组
     * @return 合并后的十六进制字节数组
     * @throws IllegalArgumentException 如果输入字节数组的长度不是偶数
     */
    public static byte[] mergeAsciiBytesToHexBytes(byte[] bytes) {
        if (bytes.length % 2 != 0) {
            throw new IllegalArgumentException("Invalid bytes length: " + bytes.length);
        }
        StringBuilder sb = new StringBuilder();
        for (byte aByte : bytes) {
            sb.append((char) aByte);
        }
        return toBytes(sb.toString().trim());
    }


    public static String asciiHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte aByte : bytes) {
            sb.append((char) aByte);
        }
        return sb.toString().trim().toUpperCase();
    }

    public static boolean isInArray(byte key, byte[] specialKey) {
        for (byte b : specialKey) {
            if (b == key) {
                return true;
            }
        }
        return false;
    }


    public static byte[] readBytesUntilSpace(ByteBuf buffer) {
        List<Byte> byteList = new ArrayList<>();
        while (buffer.isReadable()) {
            byte b = buffer.readByte();
            if (b == ASCIICode.SPACE.getCharacter()) {
                break;
            }
            byteList.add(b);
        }
        byte[] result = new byte[byteList.size()];
        for (int i = 0; i < byteList.size(); i++) {
            result[i] = byteList.get(i);
        }
        return result;
    }


    public static byte[] stringToSimpleByteArray(String str) {
        byte[] bytes = new byte[str.length()];
        for (int i = 0; i < str.length(); i++) {
            bytes[i] = (byte) str.charAt(i);
        }
        return bytes;
    }

}
